<!-- 数据项列表 -->
<template>
  <a-drawer title="可下载数据项" size="small" placement="bottom" :visible="visible" @close="modalClose" :style="{ padding: 0 }">

    <template #extra>
      <div class="allSize">总大小：<span>{{ allSize }}</span></div>
      <a @click="downLoadAll">批量下载</a>
      <!-- <input type="file" @change="downLoadAll" /> -->
    </template>

    <a-table :columns="columns.filter((col) => {
      return col.show;
    })
      " :data-source="dataSource" :pagination="false" :loading="loading" @change="onChange" rowKey="id" size="small"
      class="ks-table selection-table" sticky>
      <!--  :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }" -->
      <template #headerCell="{ column }">
        <div v-if="column.dataIndex === 'action'">
          <a-checkbox v-model:checked="Allchecked" @change="change"></a-checkbox>
        </div>
      </template>
      <template #bodyCell="{ column, index, record }">
        <template v-if="column.dataIndex === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'action'">
          <!-- <a @click="handleDownload(record)">下载</a> -->
          <a-checkbox v-model:checked="record.checked" @change="changeCheck"></a-checkbox>
        </template>
      </template>
    </a-table>
  </a-drawer>
</template>

<script>
import { DataTableMixin } from "@/mixins/DataTableMixin";
import {
  getOrderDataItems,
  downloadDataItem,
} from "@/api/dataDownloadPublish";
import { message } from "ant-design-vue";
import axios from "axios"
import { sizeAdd } from "@/utils/es_string"
export default {
  name: "DialogDownloadItems",
  mixins: [DataTableMixin],
  data() {
    return {
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          width: 50,
          align: "center",
          show: true,
        },
        {
          title: "项目名称",
          dataIndex: "projectName",
          width: 200,
          ellipsis: true,
          align: "left",
          show: true,
        },
        {
          title: "项目类型",
          dataIndex: "projectType",
          width: 100,
          align: "center",
          show: true,
        },
        {
          title: "线号",
          dataIndex: "lineName",
          width: 100,
          align: "center",
          show: true,
        },
        {
          title: "文件名",
          dataIndex: "fileName",
          width: 150,
          ellipsis: true,
          align: "center",
          show: true,
        },
        {
          title: "文件类型",
          dataIndex: "fileTypeName",
          width: 100,
          align: "center",
          show: true,
        },
        {
          title: "文件大小",
          dataIndex: "fileSize",
          width: 100,
          align: "center",
          show: true,
        },
        {
          title: "操作",
          dataIndex: "action",
          width: 80,
          align: "center",
          show: true
        },
      ],
      dataSource: [],
      loading: false,
      visible: true,
      Allchecked: false,
      selectedRowKeys: [],
      allSize: '0b'
    };
  },
  props: {
    // 订单id
    orderId: {
      type: [Number, String],
    },
    // 项目名-保存文件的文件夹名
    orderName: {
      type: String
    }
  },
  emits: ["close"],
  methods: {
    async downLoadAll() {
      const List = this.dataSource.filter(item => item.checked)
      if (!List || List.length === 0) return message.warning("请选择要下载的文件")
      const dataList = {
        fileName: this.orderName,
        projectJobId: this.orderId,
        children: []
      }
      dataList.children = List.map(item => {
        return {
          id: item.id,
          url: `${axios.defaults.baseURL}dataMana/downloadOrdersData/${item.id}`,
          // url: `${axios.defaults.baseURL}file/downloads?_filepath=`,
          // sourcePath: item.filePath,
          fileName: item.fileName,
          fileSize: item.fileSize.replaceAll(/\(|\)|约/g, ''), // 文件大小
          projectJobId: this.orderId,
        }
      })
      console.log(dataList);
      const isDownload = await window.versions.downLoadFile(dataList)
      isDownload && message.success("开始下载，请在传输中查看")
    },
    // 选择行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 全选
    change() {
      this.dataSource.map(item => item.checked = this.Allchecked)
      this.changeCheck()
    },
    modalClose() {
      this.$emit("close", false);
    },
    async getList() {
      // 获取可下载数据项
      try {
        this.loading = true;
        const res = await getOrderDataItems({ orderId: this.orderId })
        if (res && res.downloadTypeList.length > 0) {
          this.dataSource = res.downloadTypeList;
        } else {
          this.dataSource = []
        }
      } catch (error) {
        message.error(error.msg || '发生错误，请重试！')
      } finally {
        this.loading = false
      }
    },
    exportArrayToTxt() {
      let list = ['1111', '2222', '33333', '44444']
      const blob = new Blob([list.join("\n")], { type: "text/plain" });
      const url = URL.createObjectURL(blob)
      window.versions.downLoadFile(url)
      // const a = document.createElement("a");
      // a.href = url
      // a.target = "_blank"
      // a.download = 'data.txt'
      // a.click()
      // URL.revokeObjectURL(url)
    },
    // 下载
    handleDownload(record) {
      // 下载数据项
      downloadDataItem({ itemId: [record.id] }).then((downloadItems) => {
        if (downloadItems && Object.keys(downloadItems).length > 0) {
          // 获取下载链接数组（返回的数：key为下载链接、value为文件名)
          let downloadUrls = Object.keys(downloadItems);
          downloadUrls.forEach((url) => {
            // this.exportArrayToTxt()
            window.versions.downLoadFile(url)
            console.log(url);
            // if (url !== "") {
            //   window.open(url);
            // } else {
            //   this.$message.warning("下载失败，可能是未获取到文件");
            // }
            // if (res !== "") {
            //   let url = `${
            //     location.href.split("#")[0]
            //   }api/dataMana/fileStream?filePath=${res}`;
            //   let _form = document.createElement("form");
            //   document.body.append(_form);
            //   _form.method = "POST";
            //   _form.action = url;
            //   _form.target = "_blank";
            //   _form.submit();
            //   _form.remove();
            // } else {
            //   this.$message.warning("下载失败，可能是未获取到文件");
            // }
          });
        }
      });
    },
    selectedToRight() {
      const table = document.querySelector(".selection-table");
      console.log(table); // 检查是否成功获取表格

      const tbody = table.querySelector(".ant-table-tbody");
      console.log(tbody); // 检查是否成功获取表格主体

      // const selectionDom = tableDom.querySelector('.ant-table-selection-column')
      // console.log('tableDom', tableDom.removeChild(selectionDom))

    },
    changeCheck() {
      const checkedArr = this.dataSource.map(item => {
        if (item.checked && item.fileSize) {
          return item.fileSize.replaceAll(/\(|\)|约/g, '')
        }
      }).filter(Boolean)
      this.allSize = sizeAdd(checkedArr)
    }
  },
  // mounted() {
  //   this.selectedToRight()
  // },
};
</script>

<style lang="scss" scoped>
.ks-table {
  margin: -24px;
  max-width: fit-content;
}

:deep(.ant-table-sticky-holder) {
  transform: translateY(-25px);
}

.allSize {
  display: inline-block;
  transform: translateX(-20px);
  border-right: 1px solid #ebebeb;
  padding-right: 20px;

  span {
    color: red;
    font-weight: 600;
  }
}
</style>
